package burubaka.controller.mnt;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.arnx.jsonic.JSON;

import org.slim3.controller.Navigation;
import org.slim3.util.ApplicationMessage;

import burubaka.BurubakaConstants;
import burubaka.bat.RankingOrderBat;
import burubaka.common.BurubakaUtil;
import burubaka.common.controller.Controller;
import burubaka.model.Handicapping;
import burubaka.model.Tipster;
import burubaka.model.TotalResult;
import burubaka.service.HandicappingService;
import burubaka.service.TipsterService;
import burubaka.service.TotalResultService;

import com.google.appengine.api.datastore.Key;

public class TipsterController extends Controller {

	private TipsterService tipsterService = new TipsterService();
	private TotalResultService totalResultService = new TotalResultService();
	private HandicappingService handicappingService = new HandicappingService();
	private RankingOrderBat rankingOrderBat = new RankingOrderBat();

	@Override
	public Navigation init() throws Exception {

		List<Tipster> tipsterList = tipsterService.findAll();

		requestScope("tipsterList", tipsterList);

		return forward("tipster/tipsterList.jsp");
	}

	/**
	 * 編集
	 * 
	 * @return
	 * @throws Exception
	 */
	public Navigation edit() throws Exception {

		Key key = asKey("key");
		Tipster tipster = tipsterService.findByKey(key);
		requestScope("tipster", tipster);

		return forward("tipster/tipsterEdit.jsp");
	}

	/**
	 * 再集計
	 * 
	 * @return
	 * @throws Exception
	 */
	public Navigation recount() throws Exception {

		Key key = asKey("key");
		List<Handicapping> list = handicappingService.findHandicappingByAncKey(key, BurubakaConstants.CURRENT_YEAR);
		long wager = 0;
		long withdrawal = 0;
		int hit = 0;
		int bets = list.size();
		for (Handicapping handicapping : list) {
			if (handicapping.getPayOffFlag() == BurubakaConstants.FLAG_ON) {
				continue;
			}
			wager = wager + handicapping.getWager();
			withdrawal = withdrawal + handicapping.getWithdrawal();
			if (handicapping.getWithdrawal() > 0) {
				hit = hit + 1;
			}
		}
		double withdrawalRate = BurubakaUtil.getPercent(withdrawal, wager);
		double hitRate = BurubakaUtil.getPercent(hit, bets);

		TotalResult totalResult = totalResultService.findByKey(key);
		totalResult.setWager(wager);
		totalResult.setWithdrawal(withdrawal);
		totalResult.setWithdrawalRate(withdrawalRate);
		totalResult.setHit(hit);
		totalResult.setBets(bets);
		totalResult.setHitRate(hitRate);

		totalResultService.regist(totalResult);

		// 順位設定
		rankingOrderBat.execute();

		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put(BurubakaConstants.RESPONSEKEY_MESSAGE,
				ApplicationMessage.get(BurubakaConstants.MESSAGEKEY_SUCCESS, "再集計"));
		setJson(JSON.encode(resMap, true));

		return null;
	}
}
